package com.kangjia.model.m3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Page;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.model.m3.entity.Relation;
import com.kangjia.model.m3.service.RelationService;
import com.kangjia.response.AbstractResponse;
import com.kangjia.response.PageResponse;
import com.kangjia.response.SuccessResponse;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping(value = "/b/relation", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class RelationController {

	@Autowired
	private RelationService relationService;
	@Autowired
	protected JedisPool jedisPool;

	@RequestMapping(value = "/editor")
	@ResponseBody
	public AbstractResponse editor(@RequestBody Relation relation) {
		relationService.batchInsert(relation.getList());
		Jedis jedis = jedisPool.getResource();
		try {
			for (Relation r : relation.getList()) {
				if (r.getRelationId() != null) {
					String key = r.getTargetId() + "." + r.getClassify() + "." + r.getInspectStandard();
					jedis.sadd(key, r.getIndexTypeId().toString());
					jedis.sadd("relation", key);
				}
			}
		} finally {
			jedis.close();
		}
		return new SuccessResponse("操作成功");
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public AbstractResponse delete(@RequestBody Relation relation) {
		Relation entity = relationService.get(relation.getRelationId());
		if (entity != null) {
			relationService.delete(relation.getRelationId());
			Jedis jedis = jedisPool.getResource();
			try {
				String key = entity.getTargetId() + "." + entity.getClassify() + "." + entity.getInspectStandard();
				jedis.srem(key, entity.getIndexTypeId().toString());
			} finally {
				jedis.close();
			}
		}
		return new SuccessResponse("操作成功");
	}

	@RequestMapping(value = "/search")
	@ResponseBody
	public AbstractResponse search(@RequestBody Relation relation) {
		Page page = new Page();
		QueryParam param = new QueryParam(page);
		param.addParam(new Param<Integer>("classify", OperType.eq, relation.getClassify()));
		param.addParam(new Param<Integer>("inspectStandard", OperType.eq, relation.getInspectStandard()));
		param.addParam(new Param<Integer>("targetId", OperType.eq, relation.getTargetId()));
		return new PageResponse<>(relationService.search(param));
	}

}
